<template>
	<view class="page">
		<!-- <view class="my-nav-bar" :style="{marginTop:barTop+'px'}">
			
		</view> -->
		<uni-nav-bar search-icon="search" @onClickSearch="toSearch" color="#222222" background-color="#ffffff" :status-bar="true"
		 left-icon="arrowleft" :left-text="currentChatPerson.realName" @clickLeft="goBack" :fixed="true">
		</uni-nav-bar>
		<!-- 布局 -->
		<scroll-view class="chat-box">
			<view v-for="(item, key) in currentList" :key="key">
				<view v-if="item.fromId === userInfo.userId" class="right">
					<view>
						<view style="font-size:12px;color:#999;text-align:right;">{{ item.realName }}</view>
						<view class="langcon-r" v-if="item.content.type=='text'" v-html="item.content.value"></view>
						<view class="langcon-r-pic" v-else-if="item.content.type=='image'">
							<img :src="item.content.value" style='width:240px;object-fit:contain;'>
						</view>
						<view class="langcon-r-card border-radius-r" v-else-if='item.content.type=="project"||item.content.type=="demand"||item.content.type=="service"||item.content.type=="talent" ||item.content.type=="activity"'
						 @click="gotoDetial(item)">
							<image :src="item.content.pic_url" mode="aspectFill"></image>
							<view class="langcon-r-card-r">
								<view class="langcon-r-card-r-name">
									{{item.content.title}}
								</view>
								<view class="langcon-r-card-r-type">
									类型：{{item.content|cardType}}
								</view>
							</view>
						</view>
						<view class="langcon-r" v-else>
							[文件消息暂不支持请在电脑端查看]
						</view>
						<view v-else class="langcon-r" v-html="chatImage(item.content)"></view>
					</view>
					<view style="margin-left:10px;">
						<image :src="userInfo.accountHead" style="width:40px;height:40px;border-radius:50%;border:1px solid #aaa;"
						 mode="aspectFill" />
					</view>
				</view>
				<view class="chat-time" v-else-if="item.type=='time'">
					{{item.time}}
				</view>
				<view v-else class="left">
					<view>
						<image :src="currentChatPerson.accountHead" style="width:40px;height:40px;border-radius:50%;border:1px solid #aaa;" />
					</view>
					<view style="margin-left:10px;">
						<view style="font-size:12px;color:#999;">{{ currentChatPerson.realName }}</view>
						<view class="langcon-l" v-if="item.content.type=='text'" v-html="item.content.value"></view>
						<view class="langcon-l-pic" v-else-if="item.content.type=='image'">
							<img :src="item.content.value" style='width:240px;object-fit:contain;'>
						</view>
						<view class="langcon-r-card border-radius-l" v-else-if='item.content.type=="project"||item.content.type=="demand"||item.content.type=="service"||item.content.type=="talent" ||item.content.type=="activity"'
						 @click="gotoDetial(item)">
							<image :src="item.content.pic_url" mode=""></image>
							<view class="langcon-r-card-r">
								<view class="langcon-r-card-r-name">
									{{item.content.title}}
								</view>
								<view class="langcon-r-card-r-type">
									类型：{{item.content|cardType}}
								</view>
							</view>
						</view>
						<view class="langcon-l" v-else>
							[文件消息暂不支持请在电脑端查看]
						</view>
						<view v-else class="langcon-r" v-html="chatImage(item.content)"></view>
					</view>
				</view>
			</view>
		</scroll-view>
		<!-- 输入框 -->
		<view class="bottom" :style="{'bottom':inputBottom}">
			<view class="bottom-p">
				<view class="bottom-p-l"><input confirm-type="send" @confirm="clickRequest()" type="text" :adjust-position="false"
					 placeholder="发送消息" cursor-spacing="50" v-model="value" @focus="textareaFocus" @blur="textareaBlur" /></view>
				<view class="bottom-p-r">
					<view class="bottom-p-picture" @click="camera">
						<image src="https://www.innovationgloble.com/wxs/img/wx/gkxcx/icon/paizhao_1.png"></image>
					</view>
					<view class="bottom-p-camera" @click="takePicture">
						<image src="https://www.innovationgloble.com/wxs/img/wx/gkxcx/icon/tupian_1.png"></image>
					</view>
				</view>
			</view>
			<!-- 底部分类 -->
			<!-- <view class="classification"> -->
			<!-- <view>
					<image src="https://www.innovationgloble.com/wxs/img/wx/gkxcx/icon/yuyin.png"></image>
				</view> -->
			<!-- <view @click="takePicture">
					<image src="https://www.innovationgloble.com/wxs/img/wx/gkxcx/icon/tupian.png"></image>
				</view>
				<view @click="camera">
					<image src="https://www.innovationgloble.com/wxs/img/wx/gkxcx/icon/xiangji.png" style="width:25px;height:25px;"></image>
				</view> -->
			<!-- <view>
					<image src="https://www.innovationgloble.com/wxs/img/wx/gkxcx/icon/hongbao.png"></image>
				</view>
				<view>
					<image src="https://www.innovationgloble.com/wxs/img/wx/gkxcx/icon/biaoqing.png" style="width:27px;height:27px;"></image>
				</view>
				<view>
					<image src="https://www.innovationgloble.com/wxs/img/wx/gkxcx/icon/gengduo.png" style="width:27px;height:27px;"></image>
				</view> -->
			<!-- </view> -->
		</view>
		<view class="bottom-fix">

		</view>
	</view>
</template>

<script>
	import uniNavBar from '@/components/uni-nav-bar/uni-nav-bar.vue'
	import {
		mapActions,
		mapState,
		mapMutations,
		mapGetters
	} from 'vuex';
	export default {
		components: {
			uniNavBar,
		},
		filters: {
			cardType: (v) => {
				// console.log(typeof v)
				if (typeof v == 'object') {
					if (v.type == 'project') {
						return '项目'
					} else if (v.type == 'demand') {
						return '需求'
					} else if (v.type == 'service') {
						return '服务'
					} else if (v.type == 'talent') {
						return '专家'
					} else if (v.type == 'activity') {
						return '活动'
					}
				}
			}
		},
		data() {
			return {
				value: '',
				tableData: [],
				start: true,
				pageNum: 1,
				barTop: 0,
				windowHeight: 0,
				inputBottom: 0,
				baseUrl: this.$baseUrl
			};
		},
		computed: {
			...mapState('chatStore', ['currentChatPerson', 'chatListInfo', 'chatLastPage']),
			...mapState('userStore', ['userInfo']),
			...mapGetters('chatStore', ['currentMsgList']),
			currentList() {
				return this.currentMsgList(this.currentChatPerson.userId);
			},
		},
		methods: {
			...mapActions('chatStore', ['loadChatList', 'sendMsg', 'get_user_by_id', 'setUserInfo']),
			...mapMutations('chatStore', ['appendChatData', 'setCurrentPerson']),
			//删除第一位为逗号
			handleComma(val) {
				if (val && val.indexOf(',') === 0) {
					return val.substr(1)
				} else {
					return val
				}
			},
			toSearch() {
				// console.log(this.userInfo.userId, this.currentChatPerson.userId, this.currentChatPerson.accountHead, this.currentChatPerson
				// 	.realName, this.userInfo.accountHead)
				uni.navigateTo({
					url: `/pagesA/chat-content-search/chat-content-search?fromId=${this.userInfo.userId}&toId=${this.currentChatPerson.userId}&accountHead=${this.currentChatPerson.accountHead}&realName=${this.currentChatPerson.realName}&accountHeadSelf=${this.userInfo.accountHead}`
				})
			},
			isPicture(content) {
				if (typeof(content) === 'string') {
					return content.indexOf('<img') !== -1;
				}
				f
				return false;
			},
			// 点击卡片跳转详情页
			gotoDetial(v) {
				console.log(v)
				if (v.content.type == 'talent') {
					uni.navigateTo({
						url: '/pages/expert-detail/expert-detail?scene=' + v.content.id
					})
				} else if (v.content.type == 'activity') {
					uni.navigateTo({
						url: '/pages/active-detail/active-detail?scene=' + v.content.id
					})
				} else if (v.content.type == 'project') {
					uni.navigateTo({
						url: '/pages/project-detail/project-detail?scene=' + v.content.id
					})
				}
			},
			chatImage(content) {
				if (typeof(content) === 'string') {
					return content.replace('src=', 'style="width:240px;object-fit:contain;" src=' + this.$baseUrl);
				}
				return content;
			},
			sendCard(v) {
				const temp = {
					type: v.type, // text   文本   image 图片   source资源
					id: v.id, // 相关的资源ID
					title: v.name,
					pic_url: v.img
				}
				const msg = {
					fromUserId: this.userInfo.userId,
					toUserId: this.currentChatPerson.userId,
					content: JSON.stringify(temp),
					type: 'SINGLE_SENDING'
				}

				const params = {
					fromId: this.userInfo.userId,
					toId: this.currentChatPerson.userId,
					content: JSON.stringify(temp),
					sendTime: new Date()
				}
				this.appendChatData(params);
				this.sendMsg(msg);
				this.scrollToBottom();
				this.timer1 && clearInterval(this.timer1); //清空定时器

				// 自动回复
				let _self = this;
				this.timer = setTimeout(() => {
					_self.sendAutoMsg(v);
				}, 2000);
			},
			sendAutoMsg(v) {
				let _self = this
				const from = this.currentChatPerson.userId;
				const to = this.userInfo.userId;
				const {
					type
				} = v;
				if (type === 'text' || type === 'image') return;
				const temp = {
					type: 'text', // text   文本   image 图片   source资源
					value: '您好，请问有什么需要帮助的吗？'
				}
				const msg = {
					fromUserId: from,
					toUserId: to,
					content: JSON.stringify(temp),
					type: 'SINGLE_SENDING'
				}

				const params = {
					fromId: from,
					toId: to,
					content: JSON.stringify(temp),
					sendTime: new Date()
				}
				//发送socket消息
				this.sendMsg(msg);
				//清除定时器
				this.timer && clearInterval(this.timer);
				this.timer = null;
				this.timer = setTimeout(() => {
					_self.setAllRead();
				}, 1000);

			},
			clickRequest() {
				if (this.value == '') {
					uni.showToast({
						icon: 'none',
						position: 'bottom',
						title: '不能发送空白消息'
					});
				} else {
					const temp = {
						type: 'text', // text   文本   image 图片   source资源
						// source_type: 'project', // 资源类型
						// id: 0 ,// 相关的资源ID
						value: this.value
					}
					const msg = {
						fromUserId: this.userInfo.userId,
						toUserId: this.currentChatPerson.userId,
						content: JSON.stringify(temp),
						type: 'SINGLE_SENDING'
					}

					const params = {
						fromId: this.userInfo.userId,
						toId: this.currentChatPerson.userId,
						content: JSON.stringify(temp),
						sendTime: new Date()
					}
					this.appendChatData(params);
					this.sendMsg(msg);
					this.value = '';
					this.scrollToBottom();
				}
			},
			chatList(v) {
				if (this.currentChatPerson) {
					this.setAllRead();

					let params = {
						fromId: this.userInfo.userId,
						toId: this.currentChatPerson.userId,
						pageNum: this.pageNum,
						pageSize: 20,

					}
					//非下拉刷新页面拉到底部
					if (!v) {
						params.cb = () => {
							this.scrollToBottom(true);
						}
					}
					this.loadChatList(params);
				}
			},
			scrollToBottom(v) {

				if (v) {

					this.$nextTick(() => {
						let time = setTimeout(() => {
							let info = uni.createSelectorQuery().select(".chat-box");
							info.boundingClientRect(function(data) { //data - 各种参数
								uni.pageScrollTo({
									// selector: '.bottom-fix',
									scrollTop: data.height, //确保可以自动滚动到底部
									duration: 400,
									success: () => {
										clearInterval(time)
									}
								});
							}).exec()
						}, 1000)

					});
				} else {
					this.$nextTick(() => {
						let info = uni.createSelectorQuery().select(".chat-box");
						info.boundingClientRect(function(data) { //data - 各种参数
							uni.pageScrollTo({
								// selector: '.bottom-fix',
								scrollTop: data.height, //确保可以自动滚动到底部
								duration: 400,

							});
						}).exec()

					});
				}

			},
			createImgContent(fileUrl) {
				const content = "<img src=" + this.$baseUrl + fileUrl + " style='width:240px;object-fit:contain;'>";

				return content;
			},
			uploadPicture(tempFilePaths) {
				const userInfo = uni.getStorageSync('userInfo');
				uni.uploadFile({
					url: this.$baseUrl + 'imFileUploading',
					filePath: tempFilePaths[0],
					formData: {
						model: 'ImImage'
					},
					name: 'file',
					header: {
						token: userInfo.token
					},
					success: (e) => {
						let res = JSON.parse(e.data);
						if (res.ret) {
							const data = JSON.parse(res.data);
							const fileUrl = data.fileUrl;
							const temp = {
								type: 'image', // text   文本   image 图片   source资源
								// source_type: 'project', // 资源类型
								// id: 0 ,// 相关的资源ID
								value: fileUrl
							}
							let fileData = {
								fromUserId: this.userInfo.userId,
								toUserId: this.currentChatPerson.userId,
								originalFilename: 'originalFilename',
								fileUrl: fileUrl,
								type: "SINGLE_SENDING",
								content: JSON.stringify(temp),
							};


							const params = {
								fromId: this.userInfo.userId,
								toId: this.currentChatPerson.userId,
								content: JSON.stringify(temp),
								sendTime: new Date()
							}
							console.log('发送params',params)
							this.appendChatData(params);
							this.sendMsg(fileData);
							this.scrollToBottom();
						} else {
							uni.showToast({
								title: res.errmsg,
								icon: 'none'
							})
						}
					},
					fail: res => {
						uni.showToast({
							title: '图片上传失败',
							icon: 'none'
						})
					}
				})
			},
			camera() {
				let _self = this;
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['camera'], //从相册选择
					success: function(res) {
						_self.uploadPicture(res.tempFilePaths)
					}
				});
			},
			takePicture() {
				let _self = this;
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: function(res) {
						_self.uploadPicture(res.tempFilePaths)
					}
				});
			},
			setAllRead() {
				this.$request.post({
					url: 'im/set_allmsgreaded',
					data: {
						toId: this.userInfo.userId - 0,
						fromId: this.currentChatPerson.userId - 0
					}
				}).then(res => {
					this.timer && clearInterval(this.timer);
					this.timer = null;
				});


				this.$request.post({
					url: 'im/set_allmsgreaded',
					data: {
						fromId: this.userInfo.userId - 0,
						toId: this.currentChatPerson.userId - 0
					}
				}).then(res => {this.timer && clearInterval(this.timer);
					this.timer = null;});
			},
			goBack() {
				uni.navigateBack();
			},
			textareaFocus(e) {
				console.log(e)
				//点击输入框时，获取键盘高度，设置距离底部的高度为键盘的高度  
				this.inputBottom = e.detail.height + 'px';
			},
			textareaBlur(e) {
				//失去焦点时，设置距离底部为0  
				this.inputBottom = ' 0px';
			},
		},
		onShow() {
			getApp().connectWS();
		},
		onReady() {
			this.scrollToBottom();
		},
		onUnload() {
			uni.$off('refreshChat'); //在此生命周期里销毁地址改变事件的监听
		},
		onLoad(option) {
			let that = this;
			uni.getSystemInfo({
				success: function(res) {
					that.windowHeight = res.windowHeight;
				}
			});
			const isiPhoneX = wx.getStorageSync('isiPhoneX') || false;
			let offsetY = 130;
			if (isiPhoneX) {
				offsetY = 80;
			}
			uni.onKeyboardHeightChange(res => {
				if (res.height == 0)
					that.barTop = 0;
				else
					that.barTop = that.windowHeight - offsetY - res.height;
			})

			this.get_user_by_id({
				userId: option.userId || 85,
				cb: () => {
					const {
						realName,
						phoneNumber
					} = this.currentChatPerson;
					if (realName || phoneNumber) {
						this.chatList();
						uni.setNavigationBarTitle({
							title: realName || phoneNumber
						});
					}
					if (option.type) {
						//等待列表数据加载
						this.timer1 = setTimeout(function() {
							that.sendCard(option)
						}, 1000)

					}
				}
			});
			// 监听到消息 滚动到底部
			uni.$on('refreshChat', () => {
				this.scrollToBottom();
			})
		},
		onPullDownRefresh() {
			if (!this.chatLastPage) {
				this.pageNum += 1;
				this.chatList(true);
			}

			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 1000);
		}
	};
</script>

<style scoped lang="less">
	.page {
		background-color: #F5F5F5;
		width: 100%;
		min-height: 100vh;
	}

	.my-nav-bar {
		// position: fixed;
		// left: 0;
		// right: 0;
		// top: 0;
		// z-index: 99;
		// padding-bottom: 44px;

	}

	.go-back {
		width: 100%;
		height: 128rpx;
		padding-top: 30rpx;
		/* height: var(--status-bar-height);  */
		display: flex;
		align-items: center;
		background: #ffffff;
		padding-left: 30upx;
		/* margin-top: 10upx; */
		position: fixed;
		left: 0;
		top: 0;
		z-index: 99;
	}

	.go-back .back {
		width: 17upx;
		height: 31upx;

	}

	.go-back .name {
		color: #222222;
		font-size: 34upx;
		font-weight: 500;
		margin: 0 18upx 0 22upx;
	}

	.go-back .identity {
		background: rgba(255, 237, 187, .85);
		font-size: 20upx;
		color: #B6890E;
		border-radius: 8upx;
		line-height: 34upx;
		height: 34upx;
		display: inline-block;
		padding: 2upx 14upx;
	}

	.chat-box {
		padding-bottom: 75px;
		padding-top: 155upx;
		box-sizing: border-box;
	}

	.bottom {
		position: fixed;
		bottom: 0;
		width: 100%;
		background: #fff;
		padding-top: 20upx;
		padding-bottom: 20upx;
	}

	.bottom-fix {}

	.bottom-p {
		height: 74upx;
		display: flex;
		justify-content: space-between;
		flex-wrap: nowrap;
	}

	.bottom-p>view:nth-child(1) {
		width: 555upx;
		margin-left: 20upx;
		background-color: #F5F5F5;
		border-radius: 80upx;
		padding: 14upx 0 0 30upx;
		border: solid 1rpx #EDEDED;

	}

	.bottom-p-r {
		flex: 1;
		display: flex;
		justify-content: space-between;
		padding: 0 25upx;

		.bottom-p-picture {
			vertical-align: middle;
			align-items: center;
			box-sizing: border-box;
			padding-top: 8upx;

			image {
				width: 50upx;
				height: 44upx;
				vertical-align: middle;
			}
		}

		.bottom-p-camera {
			vertical-align: middle;
			align-items: center;
			box-sizing: border-box;
			padding-top: 8upx;

			image {
				width: 50upx;
				height: 44upx;
				vertical-align: middle;
			}
		}
	}

	.center {
		text-align: center;
		font-size: 24upx;
		color: #aaa;
		margin-top: 20upx;
		letter-spacing: 2upx;
	}

	.left {
		display: flex;
		flex-wrap: nowrap;
		justify-content: flex-start;
		margin-left: 20upx;
		margin-top: 20upx;
	}

	.right {
		display: flex;
		flex-wrap: nowrap;
		justify-content: flex-end;
		margin-right: 20upx;
		margin-top: 20upx;
	}

	.langcon-l-pic {
		font-size: 28upx;
		color: #414141;
		line-height: 60upx;
		border-radius: 14upx;
		margin-top: 10upx;
		margin-left: 20upx;
	}

	.langcon-l {
		display: inline-block;
		font-size: 28upx;
		color: #414141;
		line-height: 60upx;
		border-radius: 0 14upx 14upx 14upx;
		margin-top: 10upx;
		/* text-align: right; */
		padding: 6upx 20upx 6upx 20upx;
		background: #fff;
		margin-left: 20upx;
		word-break: break-word;
	}

	.langcon-l rich-text {
		word-break: break-word;
	}

	.langcon-r-pic {
		font-size: 28upx;
		color: #fff;
		line-height: 60upx;
		border-radius: 14upx;
		margin-top: 10upx;
		/* text-align: right; */
		padding: 6upx 20upx 6upx 20upx;
		/* background: ; */
		margin-left: 30upx;
	}

	.border-radius-l {
		border-radius: 0upx 20upx 20upx 20upx;
	}

	.border-radius-r {
		border-radius: 20upx 0upx 20upx 20upx;
	}


	.langcon-r {
		/* border: 2upx solid #333333; */
		font-size: 28upx;
		color: #fff;
		line-height: 60upx;
		border-radius: 14upx 0 14upx 14upx;
		margin-top: 10upx;
		/* text-align: right; */
		padding: 6upx 20upx 6upx 20upx;
		background: #008BFF;
		margin-left: 30upx;
		word-break: break-word;
		max-width: 510upx;
	}

	.langcon-r rich-text {
		word-break: break-word;
	}

	.langcon-r-pic rich-text>img {
		width: 200upx !important;
		object-fit: contain;
		border-radius: 10upx;
	}

	.langcon-l-pic rich-text>img {
		width: 200upx !important;
		object-fit: contain;
		border-radius: 10upx;
	}

	/* 	.zs {
		font-size: 12px;
		letter-spacing: 1px;
		color: #AAAAAA;
		margin-top: 5px;
		text-align: center;
	} */

	/* 分类 */
	.classification {
		display: flex;
		// flex-wrap: nowrap;
		// justify-content: space-between;
		width: 90%;
		margin: 0 auto;
		padding-top: 20upx;
	}

	.classification image {
		width: 42upx;
		height: 42upx;
		margin-right: 100upx;
	}

	.chat-time {
		text-align: center;
		font-size: 24upx;
		color: #999;

	}

	.langcon-r-card {
		width: 564upx;
		height: 182upx;
		background: rgba(255, 255, 255, 1);
		box-shadow: 0upx 4upx 6upx 0upx rgba(238, 238, 238, 0.5);
		padding: 24upx;
		display: flex;
		align-items: center;
		margin-bottom: 20upx;

		image {
			width: 188upx;
			height: 134upx;
		}

		.langcon-r-card-r {
			flex: 1;
			display: flex;
			height: 134upx;
			flex-direction: column;
			justify-content: space-between;
			margin-left: 20upx;

			.langcon-r-card-r-name {
				font-size: 30upx;
				color: #333;
				font-weight: bold;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: pre-wrap;
				word-break: break-all;
				display: -webkit-box;
				-webkit-line-clamp: 2;
				-webkit-box-orient: vertical;
				line-height: normal;
			}

			.langcon-r-card-r-type {
				font-size: 24upx;
				color: #A3A3A3;
			}
		}
	}
</style>
